package cz.muni.fi.pa165.mushroom.website.servicesImpl;


import cz.muni.fi.pa165.mushroom.website.dao.ForestDao;
import cz.muni.fi.pa165.mushroom.website.dto.ForestDto;
import cz.muni.fi.pa165.mushroom.website.dto.MushroomDto;
import cz.muni.fi.pa165.mushroom.website.entities.Forest;
import cz.muni.fi.pa165.mushroom.website.entities.Mushroom;
import cz.muni.fi.pa165.mushroom.website.services.ForestService;
import cz.muni.fi.pa165.mushroom.website.transformerAdapter.Transformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresRoles;

/**
 * @author: Pavel Démuth
 */
@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ForestServiceImpl implements ForestService {

    @Autowired
    private ForestDao forestDao;

    public ForestDao getForestDao() {
        return forestDao;
    }

    public void setForestDao(ForestDao forestDao) {
        this.forestDao = forestDao;
    }
    
    @Override
    @RequiresRoles("ROLE_USER")
    @Transactional
    public void createForest(ForestDto forestDto) {
        Forest forest = Transformer.transformForestDtoOnForest(forestDto);
        forestDao.createForest(forest);
        forestDto.setId(forest.getId());
    }

    @Override
    @RequiresRoles("ROLE_USER")
    @Transactional
    public void updateForest(ForestDto forestDto) {
        forestDao.updateForest(Transformer.transformForestDtoOnForest(forestDto));
    }

    @Override
    @RequiresRoles("ROLE_ADMIN")
    @Transactional
    public void removeForest(ForestDto forestDto) {        
        forestDao.removeForest(Transformer.transformForestDtoOnForest(forestDto));
    }

    @Override
    @RequiresRoles("ROLE_USER")
    @Transactional
    public ForestDto findForest(Long id) {
        return Transformer.transformForestOnForestDto(forestDao.findForest(id));
    }

    @Override
    @Transactional
    public List<ForestDto> listForests() {
        List<ForestDto> forestDtos = new ArrayList<>();
        for(Forest forest : forestDao.listForests()) {
            forestDtos.add(Transformer.transformForestOnForestDto(forest));
        }
        
        return forestDtos;
        
    }

    @Override
    @Transactional
    public List<MushroomDto> listFoundMushrooms(ForestDto forestDto) {
        List<MushroomDto> mushroomDtos = new ArrayList<>();
        for(Mushroom mushroom : forestDao.listFoundMushrooms
                (Transformer.transformForestDtoOnForest(forestDto))) {
            
            mushroomDtos.add(Transformer.transformMushroomOnMushroomDto(mushroom));
        }
        return mushroomDtos;
    }
}
